from fastapi import APIRouter, Depends, HTTPException, Path, Query, Body
from typing import Dict, List, Optional
import uuid

from app.services.conversation_service import ConversationService
from app.models.conversation import ConversationRenameRequest, ConversationListResponse, ConversationDeleteResponse, ConversationItem, ConversationMessageListResponse
from app.core.logger import logger

router = APIRouter(tags=["会话管理"])

# 依赖项：创建ConversationService实例
def get_conversation_service():
    return ConversationService()

@router.get("/conversations", response_model=ConversationListResponse)
async def get_conversations(
    user: str = Query(..., description="用户标识"),
    last_id: Optional[str] = Query(None, description="当前页最后面一条记录的ID"),
    limit: int = Query(20, ge=1, le=100, description="一次请求返回多少条记录，默认20条，最大100条，最小1条"),
    sort_by: Optional[str] = Query("-updated_at", description="排序字段，默认-updated_at(按更新时间倒序排列)"),
    conversation_service: ConversationService = Depends(get_conversation_service)
):
    """
    获取会话列表
    
    获取当前用户的会话列表，默认返回最近的20条
    """
    logger.debug(f"获取会话列表: user={user}, last_id={last_id}, limit={limit}, sort_by={sort_by}")
    
    try:
        response = await conversation_service.get_conversations(
            user=user,
            last_id=last_id,
            limit=limit,
            sort_by=sort_by
        )
        return response
    except Exception as e:
        logger.error(f"获取会话列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取会话列表失败: {str(e)}")

@router.delete("/conversations/{conversation_id}", response_model=ConversationDeleteResponse)
async def delete_conversation(
    conversation_id: str = Path(..., description="会话ID"),
    user: str = Body(..., description="用户标识"),
    conversation_service: ConversationService = Depends(get_conversation_service)
):
    """
    删除会话
    
    删除指定的会话
    """
    logger.debug(f"删除会话: conversation_id={conversation_id}, user={user}")
    
    try:
        result = await conversation_service.delete_conversation(
            conversation_id=conversation_id,
            user=user
        )
        return {"result": "success"}
    except Exception as e:
        logger.error(f"删除会话失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"删除会话失败: {str(e)}")

@router.post("/conversations/{conversation_id}/name", response_model=ConversationItem)
async def rename_conversation(
    conversation_id: str = Path(..., description="会话ID"),
    request: ConversationRenameRequest = Body(...),
    conversation_service: ConversationService = Depends(get_conversation_service)
):
    """
    会话重命名
    
    对会话进行重命名，会话名称用于显示在支持多会话的客户端上
    """
    logger.debug(f"重命名会话: conversation_id={conversation_id}, name={request.name}, auto_generate={request.auto_generate}, user={request.user}")
    
    try:
        response = await conversation_service.rename_conversation(
            conversation_id=conversation_id,
            name=request.name,
            auto_generate=request.auto_generate,
            user=request.user
        )
        return response
    except Exception as e:
        logger.error(f"重命名会话失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"重命名会话失败: {str(e)}")

@router.get("/messages", response_model=ConversationMessageListResponse)
async def get_messages(
    conversation_id: Optional[str] = Query(None, description="会话ID"),
    user: str = Query(..., description="用户标识"),
    first_id: Optional[str] = Query(None, description="当前页第一条聊天记录的ID"),
    limit: int = Query(20, ge=1, le=100, description="一次请求返回多少条聊天记录，默认20条"),
    conversation_service: ConversationService = Depends(get_conversation_service)
):
    """
    获取会话历史消息
    
    滚动加载形式返回历史聊天记录，第一页返回最新limit条，即：倒序返回
    """
    # 处理first_id为字符串"null"的情况
    if first_id == "null":
        first_id = None
        
    logger.debug(f"获取会话历史消息: conversation_id={conversation_id}, user={user}, first_id={first_id}, limit={limit}")
    
    try:
        response = await conversation_service.get_conversation_messages(
            conversation_id=conversation_id,
            user=user,
            first_id=first_id,
            limit=limit
        )
        return response
    except Exception as e:
        logger.error(f"获取会话历史消息失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取会话历史消息失败: {str(e)}")


